import csv
amino_acids = "ACDEFGHIKLMNPQRSTWVY"  
aa_list = list(amino_acids)
def parse_fasta(file_path):
    sequences = []
    current_seq = ""
    with open(file_path, "r") as f:
        for line in f:
            line = line.strip()
            if line.startswith(">"):
                if current_seq:
                    sequences.append(current_seq)
                    current_seq = ""
                continue
            current_seq += line.upper()  
        if current_seq:
            sequences.append(current_seq)
    return sequences

def calculate_aa_percentages(sequence):
    count = {aa: 0 for aa in amino_acids}  
    total_length = len(sequence)
    if total_length == 0:
        return {aa: 0.0 for aa in amino_acids}
    for aa in sequence:
        if aa in count:  
            count[aa] += 1
    percentage = {
        aa: (count[aa] / total_length) * 100 
        for aa in amino_acids
    }
    return percentage

def export_to_csv(results, output_path):
    headers = ["sequence_id", "length"] + aa_list
    with open(output_path, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(headers)  
        for result in results:
            row = [
                result["sequence_id"],
                result["length"]
            ] + [f"{result['percentages'][aa]:.2f}%"  for aa in aa_list]
            writer.writerow(row)

if __name__ == "__main__":
    input_fasta = "/home/zhangwt/program_text/homologs.fasta"
    output_csv = "/home/zhangwt/program_text/练习2/homologs.csv"
    all_sequences = parse_fasta(input_fasta)
    target_sequences = all_sequences[:200]
    
    results = []
    for idx, seq in enumerate(target_sequences, start=1):
        percentages = calculate_aa_percentages(seq)
        results.append({
            "sequence_id": idx,
            "length": len(seq),
            "percentages": percentages
        })
    
    export_to_csv(results, output_csv)
    print(f"结果已导出到 {output_csv}，共 {len(results)} 条序列")
